﻿using QuickManager.Code;
using QuickManager.Code.Config;
using QuickManager.Code.Config.Model;
using QuickManager.Code.SiteMgr;
using QuickManager.Code.SiteMgr.Model;
using QuickManager.UI;
using QuickManager.UI.Config;
using QuickManager.UI.Packs;
using QuickManager.UI.RequireMgr;
using QuickManager.UI.SiteMgr;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QuickManager
{
    public partial class MainForm : Form
    {
        int HotKeyID = Hotkey.GlobalAddAtom("HotkeyDisplay");
        public MainForm()
        {
            InitializeComponent();
        }

        #region 业务方法

        #endregion

        private void MainForm_Load(object sender, EventArgs e)
        {
            #region 站点管理

            //站点菜单
            this.splitContainerSiteMgr.Panel1.Controls.Add(new SiteList(this.splitContainerSiteMgr.Panel2)
            {
                Dock = DockStyle.Fill
            });

            //注册热键
            ConfigModel configHotkey = ConfigManager.GetConfig("Hotkey")
                ?? new ConfigModel()
                {
                    ConfigValue = string.Empty
                };
            if (!string.IsNullOrWhiteSpace(configHotkey.ConfigValue))
            {
                Array values = Enum.GetValues(typeof(Keys));
                foreach (int v in values)
                {
                    if (Enum.GetName(typeof(Keys), v).ToLower() == configHotkey.ConfigValue.ToLower())
                    {
                        //注册热键
                        Hotkey.RegisterHotKey(this.Handle, HotKeyID, Hotkey.KeyModifiers.Alt, (Keys)v);
                        break;
                    }
                }
            }
            #endregion
            
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == Hotkey.WM_HOTKEY)
            {
                int id = m.WParam.ToInt32();
                if (id == HotKeyID)
                {
                    //显隐主窗口
                    if (notifyIcon1.Visible)
                    {
                        notifyIcon1.Visible = false;
                        this.Show();
                        this.Activate();
                    }
                    else
                    {
                        notifyIcon1.Visible = true;
                        this.Hide();
                    }
                }
            }
        }

        private void 编译环境ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainConfig config = new MainConfig();
            config.ShowDialog();
            config.Dispose();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Dispose();
            Application.Exit();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.notifyIcon1.Visible = true;
            this.Hide();
            e.Cancel = true;
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.notifyIcon1.Visible = false;
            this.Show();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Hotkey.UnregisterHotKey(this.Handle, HotKeyID);
        }



        #region 文件合并功能


        /// <summary>
        /// 选择待合并文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmTsBtnSelectFiles_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.InitialDirectory = "D:\\";
            fileDlg.Filter = "sql files (*.sql)|*.sql|All files (*.*)|*.*";
            fileDlg.FilterIndex = 0;
            fileDlg.Multiselect = true;
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                string[] fileNames = fileDlg.FileNames;
                foreach (string f in fileNames)
                {
                    //排除重复文件
                    if (tmListFiles.Items.ContainsKey(f))
                    {
                        continue;
                    }
                    tmListFiles.Items.Add(f, f, 0);
                }
            }
        }

        /// <summary>
        /// 移除待合并文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmTsBtnDeleteFile_Click(object sender, EventArgs e)
        {
            if (tmListFiles.SelectedItems.Count > 0)
            {
                tmListFiles.Items.RemoveByKey(tmListFiles.SelectedItems[0].Text);
            }
        }

        /// <summary>
        /// 上移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmTsMoveUp_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedPreIndex = tmListFiles.SelectedItems[0].Index - 1;
                for (int i = 0; i < tmListFiles.SelectedItems.Count; i++)
                {
                    System.Windows.Forms.ListViewItem listViewItem = tmListFiles.SelectedItems[i];
                    int index = tmListFiles.SelectedItems[i].Index - 1;
                    if (index < 0)
                    {
                        return;
                    }
                    tmListFiles.Items.Remove(tmListFiles.SelectedItems[i]);
                    tmListFiles.Items.Insert(index, listViewItem);
                    listViewItem.Selected = true;
                }
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// 下移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmTsMoveDown_Click(object sender, EventArgs e)
        {
            for (int i = tmListFiles.SelectedItems.Count - 1; i > -1; i--)
            {
                System.Windows.Forms.ListViewItem listViewItem = tmListFiles.SelectedItems[i];
                int index = tmListFiles.SelectedItems[i].Index + 1;
                if (index > tmListFiles.Items.Count - 1) return;
                tmListFiles.Items.Remove(tmListFiles.SelectedItems[i]);
                tmListFiles.Items.Insert(index, listViewItem);
                listViewItem.Selected = true;
            }
        }

        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmTsClearAll_Click(object sender, EventArgs e)
        {
            tmListFiles.Items.Clear();
        }


        /// <summary>
        /// 合并并保存文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmBtnSavePathSelect_Click(object sender, EventArgs e)
        {
            SaveFileDialog fileDlg = new SaveFileDialog();
            fileDlg.InitialDirectory = "D:\\";
            fileDlg.Filter = "sql files (*.sql)|*.sql|All files (*.*)|*.*";
            fileDlg.FilterIndex = 0;
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                tmOutputPath.Text = fileDlg.FileName;
            }
        }

        /// <summary>
        /// 开始合并
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmBtnExec_Click(object sender, EventArgs e)
        {
            if (tmListFiles.Items.Count <= 0)
            {
                MessageBox.Show("没有待合并的文件！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrEmpty(tmOutputPath.Text.Trim()))
            {
                MessageBox.Show("请选择保存路径！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                //删除旧文件
                File.Delete(tmOutputPath.Text.Trim());

                //合并文件
                foreach (ListViewItem v in tmListFiles.Items)
                {
                    string contents = File.ReadAllText(v.Text, Encoding.Default);
                    string comment = string.Empty;
                    comment += "-----------------------------------------------------------------------------\r\n";
                    comment += "-- 来自 " + v.Text + "\r\n";
                    comment += "-----------------------------------------------------------------------------\r\n";
                    File.AppendAllText(tmOutputPath.Text.Trim(), comment, Encoding.Default);
                    File.AppendAllText(tmOutputPath.Text.Trim(), contents, Encoding.Default);
                    File.AppendAllText(tmOutputPath.Text.Trim(), "\r\n\r\n", Encoding.Default);
                }
                MessageBox.Show("文件合并成功！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                MessageBox.Show("输入信息有严重错误，无法进行合并！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        private void tmListFiles_DragDrop(object sender, DragEventArgs e)
        {
            MessageBox.Show("123");
        }

        #endregion

        private void tmListFiles_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Link;
        }
    }
}
